using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UIKeyRecordPanel : BaseView
{
    protected override bool RecordPos => true;
    private Button _btnClose;
    private Transform _content;
    private GameObject _templateItem;
    protected override void OnInit()
    {
        _btnClose = gameObject.transform.FindChildEx("ButtonClose").GetComponent<Button>();
        _btnClose.onClick.AddListener(() => CloseSelf());
        _content = gameObject.transform.FindChildEx("Content");
        _templateItem = gameObject.transform.FindChildEx("ItemTemplate").gameObject;
        _templateItem.SetActive(false);

        var pressCountMap = GlobalKeyboardListener.Instance.keysPressCount;
        List<Keys> list = pressCountMap.Keys.ToList();
        list.Sort((x, y) => pressCountMap[y].CompareTo(pressCountMap[x]));
        var topCount = pressCountMap[list[0]];
        for (int i = 0; i < 10; i++)
        {
            if (i < list.Count)
            {
                var item = GameObject.Instantiate(_templateItem, _content);
                item.SetActive(true);
                UpdateItem(item, list[i], pressCountMap[list[i]], topCount);
            }
        }
    }

    private void UpdateItem(GameObject item, Keys key, int count, int topCount){
        item.transform.FindChildEx("TextCount").GetComponent<TextMeshProUGUI>().text = count.ToString();

        var rectBar = item.transform.FindChildEx("ImageBar").GetComponent<RectTransform>();
        rectBar.sizeDelta = new Vector2(rectBar.sizeDelta.x, 280 * (float)count / topCount);

        var imgKey = item.transform.FindChildEx("ImageKey").GetComponent<Image>();
        var textKey = item.transform.FindChildEx("TextKey").GetComponent<TextMeshProUGUI>();
        var sprite = InputCounter.GetSpriteByKey(key);
        if (sprite)
        {
            imgKey.sprite = sprite;
            imgKey.SetNativeSize();
            imgKey.gameObject.SetActive(true);
            textKey.gameObject.SetActive(false);
        }
        else
        {
            textKey.text = key.ToString();
            imgKey.gameObject.SetActive(false);
            textKey.gameObject.SetActive(true);
        }
    }

    protected override void OnDispose()
    {

    }
}